"""
本地渲染程序。
使用前修改mmdc_path路径。
mermaid在mermaid_code中导入。
"""
import os
import subprocess
from tqdm import tqdm
from docx import Document
import docx.shared

def check_mermaid_cli():
    # 修改为你的实际路径
    mmdc_path = r"C:\Users\你的用户名\AppData\Roaming\npm\mmdc.cmd"
    try:
        subprocess.run([mmdc_path, "--version"], 
                      check=True, 
                      stdout=subprocess.PIPE, 
                      stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def render_with_progress(mermaid_code, output_docx):
    # 确保使用 mmdc.cmd 的完整路径（Windows）
    mmdc_path = os.path.join(os.environ["APPDATA"], "npm", "mmdc.cmd")
    
    with tqdm(total=5, desc="生成进度") as pbar:
        try:
            # 步骤1: 保存临时文件
            pbar.set_description("准备Mermaid代码")
            with open("temp.mmd", "w", encoding="utf-8") as f:
                f.write(mermaid_code)
            pbar.update(1)

            # 步骤2: 渲染为图片
            pbar.set_description("渲染流程图")
            subprocess.run([
                mmdc_path,
                "-i", "temp.mmd",
                "-o", "temp.png",
                "-t", "default",
                "-w", "1600",
                "-H", "1200"
            ], check=True)
            pbar.update(1)

            # 步骤3: 插入Word
            pbar.set_description("生成Word文档")
            doc = Document()
            doc.add_heading("流程图", level=1)
            doc.add_picture("temp.png", width=docx.shared.Inches(6))
            doc.save(output_docx)
            pbar.update(1)

            print(f"\n✅ 文档已生成: {os.path.abspath(output_docx)}")
            return True

        except subprocess.CalledProcessError as e:
            print(f"\n❌ 渲染失败: {e.stderr.decode() if e.stderr else str(e)}")
            return False
        finally:
            # 清理临时文件
            for file in ["temp.mmd", "temp.png"]:
                if os.path.exists(file):
                    os.remove(file)

if __name__ == "__main__":
    if not check_mermaid_cli():
        print("❌ 请手动安装: npm install -g @mermaid-js/mermaid-cli")
    else:
        mermaid_code = """
graph LR
    A[低照度相机] --> B[主动激光照明]
    B --> C[热像仪辅助]
    C --> D[多模态融合算法]
        """
        render_with_progress(mermaid_code, "output.docx")
